<?php

namespace app\common\model;

use think\Env;
use think\Model;

/**
 * 模型
 */
class MoneyRecord extends Model
{
    // 表名
    protected $name = 'money_record';
    protected $deleteTime = false;
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    const TYPE_INCOME = 1; // 收入
    const TYPE_SPEND  = 2;  // 支出

    const DETAIL_TYPE_RECHARGE = 1; // 充值
    const DETAIL_TYPE_WITHDRAW = 2; // 提现
    const DETAIL_TYPE_TRANSFER = 3; // 转账
    const DETAIL_TYPE_ORDER    = 4; // 订单
    const DETAIL_TYPE_REFUND   = 5; // 退款
    const DETAIL_TYPE_GIVING   = 6; // 赠送
    const DETAIL_TYPE_TXREFUND   = 7; // 提现退回

    const DETAIL_TYPE_MAP = [
        self::DETAIL_TYPE_RECHARGE => '充值',
        self::DETAIL_TYPE_WITHDRAW => '提现',
        self::DETAIL_TYPE_TRANSFER => '转账',
        self::DETAIL_TYPE_ORDER    => '订单',
        self::DETAIL_TYPE_REFUND   => '退款',
        self::DETAIL_TYPE_GIVING   => '赠送',
        self::DETAIL_TYPE_TXREFUND   => '提现退回',
    ];

    public function getRemarkAttr($value)
    {
        return !empty($value) ? $value : '';
    }

    public function getCreatetimeAttr($value)
    {
        return !empty($value) ? date('Y.m.d H:i',$value) : '';
    }

    public function member()
    {
        return $this->belongsTo('member', 'member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function shop()
    {
        return $this->belongsTo('shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function orders()
    {
        return $this->belongsTo('order', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 会员充值记录
     * @param int $memberId
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function memberRechargeRecord(int $memberId)
    {
        return self::where([
            'member_id' => $memberId,
            'type'      => self::TYPE_INCOME,
        ])->whereIn('detail_type', [self::DETAIL_TYPE_RECHARGE, self::DETAIL_TYPE_GIVING])->paginate();
    }

    /**
     * 商家充值写入记录
     * @param $order
     * @param $shop
     * @return MoneyRecord
     */
    public static function shopRecharge($order, $shop)
    {
        return self::create([
            'type'        => self::TYPE_INCOME,
            'money'       => $order['money'],
            'balance'     => $shop['money'],
            'shop_id'     => $shop['id'],
            'remark'      => '商家充值',
            'member_id'=>0,
            'detail_type' => self::DETAIL_TYPE_RECHARGE,
        ]);
    }


}
